//
//  PopupVietNewsDetailViewControllerViewController.m
//  VietNews
//
//  Created by Nguyen .a.Hph on 8/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "PopupVietNewsDetailViewControllerViewController.h"
#import "XHTMLParser.h"
#import "FilteredWebCache.h"
#import "Util.h"
#import "CellEntry.h"

@interface PopupVietNewsDetailViewControllerViewController ()
@property (strong, nonatomic) UIPopoverController *masterPopoverController;
@end

@implementation PopupVietNewsDetailViewControllerViewController
@synthesize webViewDetail = _webViewDetail;
@synthesize webViewHidden = _webViewHidden;
@synthesize detailItem = _detailItem;
@synthesize siteItem = _siteItem;
@synthesize masterPopoverController = _masterPopoverController;
@synthesize navigationBar = _navigationBar;
@synthesize delegate;

#pragma mark - Managing the detail item

- (UIWebView *)webViewHidden{
    if (_webViewHidden==nil){
        _webViewHidden = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    }
    return _webViewHidden;
}
- (void)setSiteItem:(Element *)newSiteItem{
    if (_siteItem != newSiteItem)
        _siteItem = newSiteItem;
}

- (void)setDetailItem:(id)newDetailItem
{
    if (_detailItem != newDetailItem) {
        _detailItem = newDetailItem;
        
        // Update the view.
        [self configureView];
    }
    
    if (self.masterPopoverController != nil) {
        [self.masterPopoverController dismissPopoverAnimated:YES];
    }        
}

- (IBAction)refreshPage:(id)sender {
    [self startLoadPage];
}

- (IBAction)closePage:(id)sender {
    [self.delegate closeUrl:self url:self.detailItem];
}

- (void)configureView
{
    //To be override
    // Update the user interface for the detail item.
    
    if (self.detailItem) {
        [self initGestureRecognizers];
        
        self.webViewDetail.delegate = self;
        self.webViewHidden.delegate = self;
        
        self.webViewHidden.tag = 1001;
        [self.view addSubview:self.webViewHidden];
        
        // Loading Indicator
        [self.webViewDetail addSubview:self.loadingIndicator];
        
        pageArr = [NSMutableArray arrayWithObject:self.detailItem];
        [self startLoadPage];
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	    
    [self configureView];
}

- (void) startLoadPage{
    [self showLoadingIndicator:@"Loading..."];
    NSRange range = [self.siteItem.art_detail rangeOfString:@"hasAjax"];
    
    CellEntry *parentObj = (CellEntry *)self.detailItem;
    
    [FilteredWebCache startFilterWebCache];
    if (range.location!=NSNotFound){
        [self.webViewHidden loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:parentObj.url]]];
    } else {
        [XHTMLParser getArticleDetailByUrl:parentObj.url site:self.siteItem viewController:self];
    }
}

- (void)viewDidUnload
{
    [self setWebViewDetail:nil];
    [self setWebViewHidden:nil];
    [self setLoadingIndicator:nil];
    [self setDetailItem:nil];
    [self setSiteItem:nil];
    
    [self setNavigationBar:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [self hideLoadingIndicator];
    
    if (webView == self.webViewHidden){
        NSLog(@"webViewHidden webViewDidFinishLoad");
        CellEntry *parentObj = (CellEntry *)self.detailItem;
        [XHTMLParser getArticleDetailByWebView:parentObj.url site:self.siteItem viewController:self];
    } else {
        NSLog(@"webViewDetail webViewDidFinishLoad");
        int currentScroll = [[NSUserDefaults standardUserDefaults]
                             integerForKey: @"currentScroll"];
        if (currentScroll!=0){
            [self.webViewDetail stringByEvaluatingJavaScriptFromString:
             [NSString stringWithFormat: @"window.scrollTo(0, %d);",
              currentScroll]];
            //store currentScroll position
            [[NSUserDefaults standardUserDefaults] setInteger:0 forKey: @"currentScroll"];
        }
    }
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    if (webView == self.webViewHidden){
        NSLog(@"didFail: %@ stillLoading:%@ error code:%i", [[webView request]URL], (webView.loading?@"NO":@"YES"), [error code]);
        if ([error code] != NSURLErrorCancelled) { //-999
            [self.webViewHidden stopLoading];
            [self performSelector:@selector(startLoadPage) withObject:nil afterDelay:1.0];
        }
        else {
            [self hideLoadingIndicator];
            [self addRightButton:NO];
        }
    } else {
        NSLog(@"webViewDetail didFailLoadWithError");
    }
}

- (void)dealloc{
    self.webViewDetail = nil;
    self.webViewHidden = nil;
    self.loadingIndicator = nil;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *urlStr = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"shouldStartLoadWithRequest: %@",urlStr);
    CellEntry *parentObj = (CellEntry *)self.detailItem;
    if ([urlStr isEqualToString:@"about:blank"] || [urlStr isEqualToString:parentObj.url])
        return YES;
    
    //Debug
    if ([urlStr hasPrefix:@"ios-log:"]) {
        NSString* logString = [[urlStr componentsSeparatedByString:@":#iOS#"] objectAtIndex:1];
        NSLog(@"log: %@", logString);
        return NO;
    }
    
    //process only url from same site
    NSString *hostname = [Util getBaseUrl:self.siteItem.url];
    if ([urlStr rangeOfString:hostname options:NSCaseInsensitiveSearch].location==NSNotFound)
        return NO;
    parentObj.url = urlStr;
    [self startLoadPage];
    if (![pageArr containsObject:urlStr])
        //[pageArr removeObject:urlStr];
        [pageArr addObject:urlStr];
    return NO;
}

#pragma mark - Gesture Recognizer Handlers

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

- (void)initGestureRecognizers{
    //add gesture
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognizerHandle:)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    swipeRight.delegate = self;
    [self.webViewDetail addGestureRecognizer:swipeRight];
    
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognizerHandle:)];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    swipeLeft.delegate = self;
    [self.webViewDetail addGestureRecognizer:swipeLeft];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognizerHandle:)];
    [tapGesture setNumberOfTapsRequired:2];
    tapGesture.delegate = self;
    [self.webViewDetail addGestureRecognizer:tapGesture];
    
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchRecognizerHandle:)];
    pinchGesture.delegate = self;
    [self.webViewDetail addGestureRecognizer:pinchGesture];
}

- (void)tapRecognizerHandle:(UITapGestureRecognizer *)sender {
    //double tap - set font size to normal (100%)
    NSString *js = [NSString stringWithFormat:@"zoom(%f)", 1.0];
    [self.webViewDetail stringByEvaluatingJavaScriptFromString:js];
}

- (void)pinchRecognizerHandle:(UIPinchGestureRecognizer *)sender {
    if (sender.state != UIGestureRecognizerStateEnded){
        //NSLog(@"%s :scale at state not end %f",__FUNCTION__,[sender scale]);
        return;
    }
    NSString *js = [NSString stringWithFormat:@"zoom(%f)", [sender scale]];
    [self.webViewDetail stringByEvaluatingJavaScriptFromString:js];
}

- (void)swipeRecognizerHandle:(UISwipeGestureRecognizer *)sender {
    int position = [pageArr indexOfObject:self.detailItem];
    if ([sender direction] == UISwipeGestureRecognizerDirectionLeft){
        NSLog(@"%s :%@",__FUNCTION__,@"left");
        if (position<[pageArr count]-1){
            self.detailItem = [pageArr objectAtIndex:(position+1)];
            [self startLoadPage];
        }
    }else {
        NSLog(@"%s :%@",__FUNCTION__,@"right");
        if (position>0){
            self.detailItem = [pageArr objectAtIndex:(position-1)];
            [self startLoadPage];
        }
    }
}

#pragma mark - right bar button
- (void)addRightButton:(BOOL)isStop{
    if (isStop)
    {
        UIBarButtonItem *stop = [[UIBarButtonItem alloc]
                                 initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(stopLoadingPage)];    
        stop.style = UIBarButtonItemStylePlain;
        [self.navigationItem setRightBarButtonItem:stop];
    }
    else {
        UIBarButtonItem *refresh = [[UIBarButtonItem alloc]
                                    initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshPage)];    
        refresh.style = UIBarButtonItemStylePlain;
        [self.navigationItem setRightBarButtonItem:refresh];
    }
}
- (void)refreshPage{
    [self startLoadPage];
}
- (void)stopLoadingPage{
    [self.webViewHidden stopLoading];
    [self.webViewDetail stopLoading];
}

#pragma mark - QueryRemoteDataDelegate
- (void)didReceiveRemoteData:(id)remoteData from:(id)remoteSender{
    //Array format: html, title
    NSArray *arrReturn = (NSArray *)remoteData;
    [FilteredWebCache endFilterWebCache];
    [self.webViewDetail loadHTMLString:[arrReturn objectAtIndex:0] baseURL:nil];
    NSString *title = [arrReturn objectAtIndex:1];
    if ([title length]>0)
        [self.navigationBar setTitle:title];
}

@end
